package com.gs.synedocket.service;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.gs.synedocket.R;
import com.gs.synedocket.util.NotificationUtil;
import com.gs.synedocket.util.StringUtil;

public class CloseService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startService(new Intent(this, SignalRService.class));
        startService(new Intent(this, GpsService.class));
        startService(new Intent(this, AutoSyncUploadService.class));
        startService(new Intent(this, AutoSyncDownloadService.class));
        startService(new Intent(this, ClearOldDataService.class));
        showNotification();
        return START_STICKY;
    }

    /**
     * 发送後台通知
     */
    private void showNotification() {
        String title = StringUtil.getString(R.string.service);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationUtil.getInstance().getNotificationManager().createNotificationChannel(NotificationUtil.getInstance().getForegroundChannel());
            Notification.Builder builder = NotificationUtil.getInstance().getForegroundNotification(this)
                    .setAutoCancel(true)
                    .setContentTitle(title)
                    .setSmallIcon(R.drawable.logo);
            startForeground(1000001, builder.build());
        } else {
            NotificationCompat.Builder builder = NotificationUtil.getInstance().getForegroundNotificationCompat(this)
                    .setAutoCancel(true)
                    .setContentTitle(title)
                    .setSmallIcon(R.drawable.logo);
            startForeground(1000001, builder.build());
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        取消显示通知
        stopForeground(true);
        SignalRService.stopSignalR();
        stopService(new Intent(this, SignalRService.class));
        AutoSyncUploadService.stopThread();
        stopService(new Intent(this, AutoSyncUploadService.class));
        AutoSyncDownloadService.stopThread();
        stopService(new Intent(this, AutoSyncDownloadService.class));
        ClearOldDataService.stopThread();
        stopService(new Intent(this, ClearOldDataService.class));
    }
}
